package com.dmw.service.impl;

import com.alipay.api.internal.util.AlipaySignature;
import com.dmw.dao.DmOrderMapper;
import com.dmw.entity.DmOrder;
import com.dmw.service.DmTradeService;
import com.dmw.util.AlipayConfig;
import com.dmw.vo.DmItemMessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018-5-22.
 */
@Service
public class DmTradeServiceImpl implements DmTradeService {
    private static final Logger logger = LoggerFactory.getLogger(DmTradeServiceImpl.class);
//    @Resource
//    private DmTradeMapper dmTradeMapper;
    @Resource
    private DmOrderMapper dmOrderMapper;
//    @Resource
//    private AlipayConfig alipayConfig;

    @Override
    public Integer insertTrade(String orderNo, String tradeNo, Integer payMethod) throws Exception {
        //预留——根据订单编号获取订单信息
        DmOrder dmOrder = loadDmOrderByOrderNo(orderNo);
        //如果订单已经支付则终止后续业务的执行
        if (2 == dmOrder.getOrderType()) {
            return 0;
        }
        DmItemMessageVo dmItemMessageVo = new DmItemMessageVo();
        dmItemMessageVo.setTradeNo(tradeNo);
        dmItemMessageVo.setOrderNo(orderNo);
        dmItemMessageVo.setItemId(dmOrder.getItemId().toString());
        dmItemMessageVo.setUserId(dmOrder.getUserId().toString());
        dmItemMessageVo.setAmount(dmOrder.getTotalAmount());
        dmItemMessageVo.setPayMethod(payMethod);
//        DmTrade dmTrade = new DmTrade();
//        dmTrade.setTradeNo(tradeNo);
//        dmTrade.setOrderNo(orderNo);
//        dmTrade.setPayMethod(payMethod);

//        return dmTradeMapper.insertDmTrade(dmItemMessageVo);
        return 0;
    }

    @Override
    public DmOrder loadDmOrderByOrderNo(String orderNo) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderNo", orderNo);
        //根据订单编号查询订单——待引入
        List<DmOrder> dmOrders = dmOrderMapper.getDmOrderListByMap(params);
        if (dmOrders.size() == 0) {
//            throw new BaseException(PayErrorCode.PAY_NO_EXISTS);
        }
        return dmOrders.get(0);
    }

    @Override
    public boolean asyncVerifyResult(Map<String, Object> params) throws Exception {
        Map<String, String> verifyParams = new HashMap<String, String>();
        Map<String, String[]> requestParams = (Map<String, String[]>) params.get("requestParams");
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            verifyParams.put(name, valueStr);
        }
        // 计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(verifyParams, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        return verify_result;
    }

    public boolean syncVerifyResult(Map<String, String[]> requestParams) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        StringBuilder sb = new StringBuilder();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            sb.append(name+"="+valueStr+"&");
            params.put(name, valueStr);
        }
        logger.info(sb.toString());
        // 计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(params,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        logger.info(verify_result+"");
        return verify_result;
    }

//    @Override
//    @RabbitListener(queues = Constants.RabbitQueueName.TO_UPDATED_ORDER_QUEUE)
//    public void testRabbitMq(DmItemMessageVo dmItemMessageVo) throws Exception {
//        logger.info(">>>>>>>>>>>>>>>>>收到消息 update begin "+ dmItemMessageVo.getOrderNo());
//        try {
//            //找到对应订单
//            DmOrder dmOrder = restDmOrderClient.getDmOrderByOrderNo(dmItemMessageVo.getOrderNo());
//            //更新对应的订单状态为支付成功
//            dmOrder.setOrderType(Constants.OrderStatus.SUCCESS);
//            //更新支付类型
//            dmOrder.setPayType(dmItemMessageVo.getPayMethod() + "");
//            //更新编号
//            if (dmItemMessageVo.getPayMethod() == Constants.PayMethod.WEIXIN) {
//                dmOrder.setWxTradeNo(dmItemMessageVo.getTradeNo());
//            } else {
//                dmOrder.setAliTradeNo(dmItemMessageVo.getTradeNo());
//            }
//            dmOrder.setUpdatedTime(new Date());
//            //更新数据库
//            restDmOrderClient.qdtxModifyDmOrder(dmOrder);
//
//            logger.info(">>>>>>>>>>>>>>>>>收到消息 update success"+ dmItemMessageVo.getOrderNo());
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
//    }

    @Override
    public boolean processed(String orderNo, Integer flag) throws Exception {
//        return restDmOrderClient.processed(orderNo, flag);
        return true;
    }

}
